import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 60000, // 过期时间
    headers:{"Content-Type":"application/x-www-form-urlencoded"},
    withCredentials:true,
})

service.interceptors.request.use(
    config => {
        // 发送请求之前做的
        const token = !store.getters.token ? getToken('token') : store.getters.token
        if (token) {
            config.headers['token'] = token
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code === 405) {
            Message.error('无效的会话，或者登录已过期，请重新登录。')
            location.href = '/#/user/login'
        } else if (res.code === 403) {
            Message.error('没有权限访问。')
        }
        if (res.code !== 200 && res.code !== 405) {
            Message({
                message: res.msg || '错误',
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject()
        } else {
            return res.data
        }
    },
    error => {
        Message({
            message: '请求失败',
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)
export default service
